package com.briup.cms.web.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.utils.JwtUtil;
import com.briup.cms.utils.MessageStatus;
import com.briup.cms.utils.SecurityUtils;
import com.briup.cms.utils.UserInfo;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 * @Description
 * @date 2021/7/17 19:52
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }

        // 从 http 请求头中取出 Authorization 字段的值，也是jwt的token值
        String token = httpServletRequest.getHeader("Authorization");

        if (token == null) {
            throw new CustomerException(MessageStatus.USER_TOKEN_NOT_EXIST);
        }

        // 验证 token
        try {
            JwtUtil.checkSign(token);
        } catch (JWTVerificationException e) {
            throw new CustomerException(MessageStatus.USER_TOKEN_INVALID);
        }




        //日志功能
        String uri = httpServletRequest.getRequestURI();
        String method = httpServletRequest.getMethod();
        Map<String, Object> userInfo = JwtUtil.getInfo(token);

        userInfo.put("uri",uri);
        userInfo.put("method",method);

        UserInfo.setUserinfo(userInfo);

        return true;
    }



}
